program test_data_fit

    use data_fit, only: data_fit_init, data_fit_approximate, data_fit_finalize

    implicit none

    integer :: num_data
    integer :: num_dim
    real, allocatable :: x(:,:), y(:)
    integer :: max_exponent
    real, allocatable :: c(:)
    integer :: i, j
    character(10) :: argv
    character(20) :: file_name
    logical :: alive

    if(command_argument_count() /= 4) then
        write(*, *) "usage error"
        write(*, *) "    test_data_fit <num_data> <num_dim> <max_exponent> <input data file>"
        stop
    end if
    call get_command_argument(1, argv)
    read(argv, "(i)") num_data
    call get_command_argument(2, argv)
    read(argv, "(i)") num_dim
    call get_command_argument(3, argv)
    read(argv, "(i)") max_exponent
    call get_command_argument(4, file_name)

    allocate(x(num_dim,num_data))
    allocate(y(num_data))

    inquire(file=file_name, exist=alive)
    if(alive == .false.) then
        write(*, *) "file ", trim(file_name), " not found"
        stop
    end if

    open(10, file=file_name, status="old")
    do j = 1, num_data
        do i = 1, num_dim
            read(10, "(f)", advance="no") x(i,j)
        end do
        read(10, "(f)") y(j)
    end do
    close(10)

    call data_fit_init("findfit", num_dim, max_exponent)

    call data_fit_approximate(num_data, x, y, max_exponent, c)

    call data_fit_finalize

    write(*, *) "parameters:"
    write(*, *) c

    stop
end program test_data_fit
